package com.example.demo.service.impl;

import com.example.demo.entity.Manager;
import com.example.demo.exception.BusinessException;
import com.example.demo.exception.ErrorCode;
import com.example.demo.mapper.ManagerMapper;
import com.example.demo.mapper.RuleMapper;
import com.example.demo.service.ManagerService;
import com.example.demo.utils.ArrayUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.stream.Collectors;

@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private RuleMapper ruleMapper;

    @SuppressWarnings("unused")
    private final ObjectMapper objectMapper = new ObjectMapper()
        .registerModule(new JavaTimeModule());

    @Override
    public Manager createManager(Manager manager) {
        // 检查用户名是否已存在
        Map<String, Object> params = new HashMap<>();
        params.put("keyword", manager.getUsername());
        List<Map<String, Object>> list = managerMapper.selectManagerList(params);
        if (!list.isEmpty()) {
            throw new BusinessException(ErrorCode.USER_ALREADY_EXISTS);
        }

        // 设置创建时间
        manager.setCreate_time(new Date());
        manager.setUpdate_time(new Date());
        
        // 插入数据
        managerMapper.insertManager(manager);
        return manager;
    }

    @Override
    public Manager updateManager(Manager manager) {
        // 检查用户名是否已存在（排除自己）
        Map<String, Object> params = new HashMap<>();
        params.put("id", manager.getId());
        List<Map<String, Object>> list = managerMapper.selectManagerList(params);
        if (list.isEmpty()) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }

        // 设置更新时间
        manager.setUpdate_time(new Date());
        
        // 更新数据
        managerMapper.updateManager(manager);
        return manager;
    }

    @Override
    public boolean deleteManager(Integer id) {
        // 检查ID是否存在
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        List<Map<String, Object>> list = managerMapper.selectManagerList(params);
        if (list.isEmpty()) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }

        // 删除数据
        managerMapper.deleteManager(id);
        return true;
    }

    @Override
    public Map<String, Object> getManagerList(Integer page, Integer limit, String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("keyword", keyword);
        
        // 使用PageHelper分页
        PageHelper.startPage(page, limit);
        List<Map<String, Object>> list = managerMapper.selectManagerList(params);
        
        // 处理角色信息
        List<Map<String, Object>> processedList = list.stream().map(item -> {
            Map<String, Object> manager = new HashMap<>(item);
            Map<String, Object> role = new HashMap<>();
            role.put("id", item.get("role_id"));
            role.put("name", item.get("role_name"));
            manager.put("role", role);
            return manager;
        }).collect(Collectors.toList());

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(processedList);
        Map<String, Object> data = new HashMap<>();
        data.put("list", pageInfo.getList());
        data.put("totalCount", pageInfo.getTotal());
        return data;
    }

    @Override
    public boolean updateManagerStatus(Integer id, Integer status) {
        // 检查ID是否存在
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        List<Map<String, Object>> list = managerMapper.selectManagerList(params);
        if (list.isEmpty()) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }

        // 更新状态
        managerMapper.updateManagerStatus(id, status);
        return true;
    }

    @Override
    public Manager getManagerByUsername(String username) {
        Manager manager = managerMapper.selectManagerByUsername(username);
        if (manager == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }
        return manager;
    }

    @Override
    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        // 获取用户信息
        Manager manager = managerMapper.selectManagerById(userId);
        if (manager == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }

        // 验证旧密码
        if (!manager.getPassword().equals(oldPassword)) {
            throw new BusinessException(ErrorCode.USER_PASSWORD_ERROR);
        }

        // 更新密码
        manager.setPassword(newPassword);
        manager.setUpdate_time(new Date());
        managerMapper.updateManagerPassword(manager.getId(), manager.getPassword(), manager.getUpdate_time());
        return true;
    }

    @Override
    public Map<String, Object> getManagerInfo(Integer userId) {
        
        
        // 获取管理员基本信息
        Map<String, Object> managerInfo = managerMapper.selectManagerInfo(userId);
        if (managerInfo == null || managerInfo.isEmpty()) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }

        // 获取权限菜单ID列表
        String ruleIdsStr = (String) managerInfo.get("ruleIds");
        if (ruleIdsStr == null || ruleIdsStr.isEmpty()) {
            throw new BusinessException(ErrorCode.PERMISSION_DENIED);
        }

        // 转换ruleIds为List<Integer>
        List<Integer> ruleIds = Arrays.stream(ArrayUtils.stringToIntArray(ruleIdsStr))
            .collect(Collectors.toList());

        // 获取所有权限菜单
        List<Map<String, Object>> ruleList = ruleMapper.selectRuleListByIds(ruleIds);

        // 将权限菜单分为menuList和actionList
        List<Map<String, Object>> menuList = ruleList.stream()
            .filter(rule -> "1".equals(rule.get("menu").toString()))
            .collect(Collectors.toList());

        List<Map<String, Object>> actionList = ruleList.stream()
            .filter(rule -> "0".equals(rule.get("menu").toString()))
            .collect(Collectors.toList());

        // 构建menuTree
        List<Map<String, Object>> menuTree = buildMenuTree(menuList);

        // 处理actionList
        List<String> ruleNames = actionList.stream()
            .map(rule -> rule.get("condition") + "," + rule.get("method"))
            .collect(Collectors.toList());

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("id", managerInfo.get("userId"));
        result.put("username", managerInfo.get("username"));
        result.put("avatar", managerInfo.get("avatar"));
        result.put("super", managerInfo.get("super"));
        result.put("role", new HashMap<String, Object>() {{
            put("id", managerInfo.get("roleId"));
            put("name", managerInfo.get("roleName"));
        }});
        result.put("menus", menuTree);
        result.put("ruleNames", ruleNames);

        
        return result;
    }

    @SuppressWarnings("unchecked")
    private List<Map<String, Object>> buildMenuTree(List<Map<String, Object>> menuList) {
        // 按rule_id和order排序
        menuList.sort((m1, m2) -> {
            int compare = Integer.compare(
                (Integer) m1.get("rule_id"),
                (Integer) m2.get("rule_id")
            );
            if (compare == 0) {
                compare = Integer.compare(
                    (Integer) m1.get("order"),
                    (Integer) m2.get("order")
                );
            }
            return compare;
        });

        // 构建树形结构
        Map<Integer, Map<String, Object>> menuMap = new HashMap<>();
        List<Map<String, Object>> rootMenus = new ArrayList<>();

        // 将所有菜单放入map
        for (Map<String, Object> menu : menuList) {
            menuMap.put((Integer) menu.get("id"), menu);
        }

        // 构建树形结构
        for (Map<String, Object> menu : menuList) {
            Integer parentId = (Integer) menu.get("rule_id");
            if (parentId == 0) {
                rootMenus.add(menu);
            } else {
                Map<String, Object> parentMenu = menuMap.get(parentId);
                if (parentMenu != null) {
                    List<Map<String, Object>> children = 
                        (List<Map<String, Object>>) parentMenu.computeIfAbsent(
                            "child", k -> new ArrayList<>());
                    children.add(menu);
                }
            }
        }

        return rootMenus;
    }
}
